package cn.pconline.autoclub.web.admin;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.gelivable.auth.entity.GeliSession;
import org.gelivable.auth.entity.GeliUser;
import org.gelivable.webmvc.JSONBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.pconline.autoclub.entity.Gift;
import cn.pconline.autoclub.entity.GiftConversion;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.GiftService;
import cn.pconline.autoclub.service.MessageService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.WebUtils;

/**
 *
 * @author ppc
 */
@Controller
@RequestMapping(value = "/admin")
public class AdminGiftController {

    @Autowired
    private GiftService giftService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserService userService;
    private static final Logger log = LoggerFactory.getLogger(AdminGiftController.class);

    /**
     * 成功返回消息
     *
     * @param resp
     * @param navTabId
     * @param msg
     * @param callbackType closeCurrent 关闭当前tab forward reload
     */
    private void successMsg(HttpServletResponse resp, String navTabId, String msg, String callbackType) {
        try {
            resp.setCharacterEncoding("UTF-8");
            PrintWriter out = resp.getWriter();
            out.println(new JSONBuilder().put("statusCode", 200).put("message", msg).put("navTabId", navTabId).put("callbackType", callbackType).toString());
        } catch (IOException ex) {
            log.error("set successMsg fail!", ex);
        }
    }

    private void errorMsg(HttpServletResponse resp, String msg) {
        try {
            resp.setCharacterEncoding("UTF-8");
            PrintWriter out = resp.getWriter();
            out.println(new JSONBuilder().put("statusCode", 300).put("message", msg).toString());
        } catch (IOException ex) {
            log.error("set errorMsg fail!", ex);
        }
    }

    private boolean checkGiftInfo(String name, int gold, int total, int seq, String url, HttpServletResponse resp) {
        if (StringUtils.isBlank(name) || StringUtils.length(name) > 12) {
            errorMsg(resp, "请输入正确的礼品名称");
            return false;
        }
        if (gold <= 0) {
            errorMsg(resp, "所需金币必须大于0");
            return false;
        }
        if (total <= 0) {
            errorMsg(resp, "商品数量必须大于0");
            return false;
        }
        if (seq <= 0) {
            errorMsg(resp, "序号必须大于0");
            return false;
        }
        if (StringUtils.isBlank(url)) {
            errorMsg(resp, "礼品图片不能为空");
            return false;
        }
        return true;
    }

    /**
     * 创建礼品
     *
     * @param request
     * @param resp
     */
    @RequestMapping(value = "/gift/create", method = RequestMethod.POST)
    public void createGift(HttpServletRequest request, HttpServletResponse resp) {
        String name = WebUtils.param(request, "name", "");
        int total = WebUtils.paramInt(request, "total", 0, 0, Integer.MAX_VALUE);
        int gold = WebUtils.paramInt(request, "gold", 0, 0, Integer.MAX_VALUE);
        String url = WebUtils.param(request, "url", "");
        int status = WebUtils.paramInt(request, "status", Gift.STATUS_DOWN);
        int seq = WebUtils.paramInt(request, "seq", 0);
        String link = WebUtils.param(request, "link", "");
        if (!checkGiftInfo(name, gold, total, seq, url, resp)) {
            return;
        }
        GeliUser geliUser = GeliSession.getCurrentUser();
        if (geliUser != null) {
            Gift gift = new Gift();
            gift.setName(name);
            gift.setGiftUrl(url);
            gift.setGold(gold);
            gift.setTotal(total);
            gift.setCurNum(total);
            gift.setSeq(seq);
            gift.setCreateBy(geliUser.getUserId());
            gift.setStatus(status);
            gift.setLink(link);
            long id = giftService.createGift(gift);
            if (id > 0) {
                successMsg(resp, "list-gift", "创建成功", "closeCurrent");
            } else {
                errorMsg(resp, "创建失败");
            }
        } else {
            errorMsg(resp, "请登陆后操作");
        }
    }

    /**
     * 礼品详情
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/gift/giftDetail.do")
    public String giftDetail(HttpServletRequest req, HttpServletResponse resp) {
        long giftId = WebUtils.paramLong(req, "giftId", 0);
        Gift gift = giftService.find(giftId);
        req.setAttribute("gift", gift);
        return "admin/gift/update";
    }

    /**
     * 礼品列表
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/gift/listGift.do")
    public String list(HttpServletRequest req, HttpServletResponse resp) {
        int pageNo = WebUtils.paramInt(req, "pageNum", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 20);
        Pager<Gift> pager = giftService.listGift(pageNo, pageSize);
        req.setAttribute("pager", pager);
        return "admin/gift/list";
    }

    /**
     * 修改礼品信息
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/gift/update")
    public void updateGift(HttpServletRequest req, HttpServletResponse resp) {
        long giftId = WebUtils.paramLong(req, "giftId", 0);
        String name = WebUtils.param(req, "name", "");
        int total = WebUtils.paramInt(req, "total", 0);
        int curNum = WebUtils.paramInt(req, "curNum", 0);
        int gold = WebUtils.paramInt(req, "gold", 0);
        String url = WebUtils.param(req, "url", "");
        int status = WebUtils.paramInt(req, "status", Gift.STATUS_DOWN);
        int seq = WebUtils.paramInt(req, "seq", 0);
        String link = WebUtils.param(req, "link", "");
        if (!checkGiftInfo(name, gold, total, seq, url, resp)) {
            return;
        }
        Gift gift = giftService.find(giftId);
        if (gift == null) {
            errorMsg(resp, "giftId有误!");
            return;
        }
        gift.setName(name);
        gift.setGiftUrl(url);
        gift.setTotal(total);
        gift.setCurNum(curNum);
        gift.setStatus(status);
        gift.setGold(gold);
        gift.setSeq(seq);
        gift.setLink(link);
        long count = giftService.updateGift(gift);
        if (count > 0) {
            successMsg(resp, "list-gift", "修改成功", "closeCurrent");
        } else {
            errorMsg(resp, "修改失败");
        }
    }

    /**
     * 修改礼品状态
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/gift/editStatus", method = RequestMethod.POST)
    public void editStatus(HttpServletRequest req, HttpServletResponse resp) {
        int status = WebUtils.paramInt(req, "status", Gift.STATUS_DOWN);
        long giftId = WebUtils.paramLong(req, "giftId", 0);
        Gift gift = giftService.find(giftId);
        if (gift == null) {
            errorMsg(resp, "giftId有误!");
            return;
        }
        gift.setStatus(status);
        long count = giftService.updateGift(gift);
        if (count > 0) {
            successMsg(resp, "list-gift", "操作成功", null);
        } else {
            errorMsg(resp, "修改失败");
        }
    }

    /**
     * 查询兑换记录
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/gift/listConversion")
    public String listConversion(HttpServletRequest req, HttpServletResponse resp) {
        long userId = WebUtils.paramLong(req, "userId", 0);
        long giftId = WebUtils.paramLong(req, "giftId", 0);
        String truename = WebUtils.param(req, "truename", "");
        int status = WebUtils.paramInt(req, "status", GiftConversion.STATUS_NOSELECT);
        String beginDate = WebUtils.param(req, "beginDate", "");
        String endDate = WebUtils.param(req, "endDate", "");
        int pageNo = WebUtils.paramInt(req, "pageNum", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", 20);
        Pager<GiftConversion> pager = giftService.listConversionWithGift(userId, giftId, truename, status, beginDate, endDate, pageNo, pageSize);
        req.setAttribute("pager", pager);
        req.setAttribute("truename", truename);
        req.setAttribute("status", status);
        req.setAttribute("beginDate", beginDate);
        req.setAttribute("endDate", endDate);
        return "admin/gift/listConversion";
    }
    
    /**
     * 兑换记录导出
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/gift/exportConversions.do", produces = {"application/octet-stream"})
    public void dailyGeneralSituationExport(HttpServletRequest req, HttpServletResponse resp) {
    	 long userId = WebUtils.paramLong(req, "userId", 0);
         long giftId = WebUtils.paramLong(req, "giftId", 0);
         String truename = WebUtils.param(req, "truename", "");
         int status = WebUtils.paramInt(req, "status", GiftConversion.STATUS_NOSELECT);
         String beginDate = WebUtils.param(req, "beginDate", "");
         String endDate = WebUtils.param(req, "endDate", "");
         int pageNo = WebUtils.paramInt(req, "pageNum", 1);
         int pageSize = WebUtils.paramInt(req, "pageSize", 20);
         Pager<GiftConversion> pager = giftService.listConversionWithGift(userId, giftId, truename, status, beginDate, endDate, pageNo, pageSize);
        
        //导出excel
        String[] cellString = new String[]{"ID", "用户昵称", "真实姓名", "手机号码", "详细地址","邮编", "申请礼品", "兑换数量", "申请时间", "处理状态"};
        HSSFWorkbook work = new HSSFWorkbook();
        HSSFSheet sheet = work.createSheet("兑换记录列表");
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < cellString.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(cellString[i]);
        }
        /**
         * 根据分页数据生成excel文件
         */
        for (int curPage = pageNo; curPage <= pager.getPageCount(); curPage++) {
            // 数据一页一页加载
            if (curPage != pageNo) {
                pager = giftService.listConversionWithGift(userId, giftId, truename, status, beginDate, endDate, curPage, pageSize);
            }   
	        for (int i = 0; i < pager.getResultList().size(); i++) {
	        	    GiftConversion g = pager.getResultList().get(i);
	        	    HSSFRow rowData = sheet.createRow(((curPage - 1) * pageSize) + i + 1);
	                rowData.createCell(0).setCellValue(g.getConversionId());
	                rowData.createCell(1).setCellValue(g.getUser().getNickname());
	                rowData.createCell(2).setCellValue(g.getTrueName());
	                rowData.createCell(3).setCellValue(g.getPhone());
	                rowData.createCell(4).setCellValue(g.getAddress());
	                rowData.createCell(5).setCellValue(g.getPostcode());
	                rowData.createCell(6).setCellValue(g.getGift().getName());
	                rowData.createCell(7).setCellValue(g.getNum());
	                rowData.createCell(8).setCellValue(DateUtils.formatDetail(g.getCreateAt()));
	                rowData.createCell(9).setCellValue(g.getStatus() == 1 ? "已发货" : g.getStatus()==0 ? "待发货" : g.getStatus()==-1 ? "驳回" : "待付款");
	            }
        }

        try {
            //设置返回数据类型
            resp.setContentType("application/vnd.ms-excel;charset=GBK");
            //设置返回的文件名
            resp.setHeader("Content-Disposition", 
            		"attachment;Filename=ConversionList.xls");
            OutputStream out = resp.getOutputStream();
            work.write(out);
            out.flush();
            out.close();
        } catch (IOException ex) {
            log.error("Export conversions fail!", ex);
        }
    }

    /**
     * 修改礼品状态 TODO 像这种状态的操作，应该是拆成几个方法（之前崇锜有讨论过的）
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/gift/editConversionStatus", method = RequestMethod.POST)
    public void editConversionStatus(HttpServletRequest req, HttpServletResponse resp) {
        int status = WebUtils.paramInt(req, "status", Gift.STATUS_DOWN);
        String rejectMsg = WebUtils.param(req, "rejectMsg", "");
        long conversionId = WebUtils.paramLong(req, "conversionId", 0);
        GiftConversion conversion = giftService.findConversion(conversionId);
        if (conversion == null) {
            errorMsg(resp, "找不到该条记录");
            return;
        }
        int oldStatus = conversion.getStatus();
        boolean isRestitution = false;
        if (oldStatus == GiftConversion.STATUS_NOSEND && status == GiftConversion.STATUS_DOWN) {
            // 与任务接口对接返回金币,成功修改订单状态 只有金币数大于0才会调任务系统接口,小于0直接当扣金币成功
            if (conversion.getGold() > 0) {
                int code = giftService.restorationGold(conversion.getLogId(), conversion.getUserId());
                if (code == Gift.STATUS_GOLD_OK) {
                    isRestitution = true;
                } else {
                    isRestitution = false;
                }
            } else {
                isRestitution = true;
            }
        }
        Gift gift = null;
        //驳回时增加驳回理由
        if (status == GiftConversion.STATUS_DOWN) {
            //成功返回金币否则返回
            if (isRestitution == true) {
                //驳回返回金币增加库存
                gift = giftService.find(conversion.getGiftId());
                if (gift != null) {
                    gift.setCurNum(gift.getCurNum() + 1);
                    giftService.updateGift(gift);
                }
                conversion.setRejectMsg(rejectMsg);
            } else {
                errorMsg(resp, "返回金币不成功,请联系管理员");
                return;
            }
        }

        if (oldStatus == GiftConversion.STATUS_DOWN) {
            errorMsg(resp, "该记录已经驳回无法再修改");
            return;
        }
        //设置发货时间
        if (status == GiftConversion.STATUS_SEND) {
            conversion.setShipmentsAt(new Date());
        }
        if (status == GiftConversion.STATUS_NOSEND) {
            conversion.setShipmentsAt(null);
        }
        conversion.setStatus(status);
        long count = giftService.updateConversion(conversion);
        if (count > 0) {
            if (status == GiftConversion.STATUS_DOWN) {
                User user = userService.findUser(conversion.getUserId());
                if (user != null && gift != null) {
                    //驳回发送消息给用户
                    messageService.send(user, MessageService.GIFT_REJECT_MSG, gift.getName(), conversion.getRejectMsg());
                }
                successMsg(resp, "list-conversion-query", "操作成功", "closeCurrent");
            } else {
                successMsg(resp, "list-conversion-query", "操作成功", null);
            }
        } else {
            errorMsg(resp, "修改失败");
        }
    }

    /**
     * 驳回理由页面跳转
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/gift/rejectMsg")
    public String rejectMsg(HttpServletRequest req, HttpServletResponse resp) {
        long conversionId = WebUtils.paramLong(req, "conversionId", 0);
        int isRead = WebUtils.paramInt(req, "isRead", 0);
        GiftConversion conversion = giftService.findConversion(conversionId);
        if (conversion == null) {
            errorMsg(resp, "找不到该申请记录");
            return "";
        }
        req.setAttribute("isRead", isRead);
        req.setAttribute("conversion", conversion);
        return "admin/gift/rejectMsg";
    }

    /**
     * 页面跳转
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/gift/goToCreate", method = RequestMethod.GET)
    public String goToCreate(HttpServletRequest req, HttpServletResponse resp) {
        return "admin/gift/create";
    }
}
